package com.awesome.videodemo.util;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;

/**
 * Author: zhangjingfang
 * Email:zhangjingfang@jeejio.com
 * Date: 2022/7/7
 * Description: 视频工具类
 */
public class VideoUtil {
    public static Bitmap getFrameFromIndex(String path, int frameIndex) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(path);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
            int frameCount = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT));
            if (frameIndex <= frameCount) {
                return retriever.getFrameAtIndex(frameIndex);
            }
        }
        return null;
    }

    public static int getFrameCount(String path) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(path);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            return Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT));
        }
        return 0;
    }

    public static Bitmap getFrameFromTime(String path, int time) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(path);
        int duration = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        if (time <= duration) {
            return retriever.getFrameAtTime(time);
        }
        return null;
    }

}
